package com.yeskery.nut.webhook.biz;

import com.yeskery.nut.annotation.bean.Component;
import com.yeskery.nut.annotation.environment.Value;
import com.yeskery.nut.application.ApplicationMetadata;
import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.bean.aware.NutApplicationAware;
import com.yeskery.nut.util.IPUtils;
import com.yeskery.nut.util.StringUtils;

import java.util.Collection;

/**
 * Server biz
 * @author Yeskery
 * 2023/6/8
 */
@Component
public class ServerBiz implements NutApplicationAware {

    @Value("${server.url:}")
    private String serverUrl;

    private ApplicationMetadata applicationMetadata;

    /**
     * 获取服务url
     * @param host 客户端传递的host主机名
     * @return 服务url
     */
    public String getServerUrl(String host) {
        if (!StringUtils.isEmpty(host)) {
            return host;
        }
        if (!StringUtils.isEmpty(serverUrl)) {
            return serverUrl;
        }
        return IPUtils.getAllLocalIp().values().stream().flatMap(Collection::stream)
                .filter(s -> !StringUtils.isEmpty(s)).findFirst().orElse("127.0.0.1")
                + ":" + applicationMetadata.getServerPort();
    }

    @Override
    public void setNutApplication(NutApplication nutApplication) {
        applicationMetadata = nutApplication.getApplicationMetadata();
    }
}
